package top.songxs.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import top.songxs.base.BaseDao;
import top.songxs.base.BaseServiceImpl;
import top.songxs.dao.AdminRoleDao;
import top.songxs.dao.RoleDao;
import top.songxs.entity.AdminRole;
import top.songxs.entity.Role;
import top.songxs.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;

    @Override
    @Transactional(readOnly = true)
    public List<Role> findAll() {
        return this.roleDao.findAll();
    }


    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }


    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
        //获取所有的角色
        List<Role> roleList = this.roleDao.findAll();
        //获取当前用户的角色id列表
        List<Long> roleIdList= this.adminRoleDao.findRoleByAdminId(adminId);
        //根据当前用户的角色id列表将所有角色分为两部分：已分配、未分配
        List<Role> noAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList = new ArrayList<>();
        for(Role role:roleList){
            if(roleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else{
                noAssignRoleList.add(role);
            }
        }
        //返回数据
        Map roleMap = new HashMap();
        roleMap.put("noAssignRoleList", noAssignRoleList);
        roleMap.put("assignRoleList", assignRoleList);
        return roleMap;
    }

    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long [] roleIds) { //1,4,6,null
        //删除之前的角色列表
        this.adminRoleDao.deleteByAdminId(adminId);
        //添加新赋予的角色列表
        if(roleIds!=null){
            for (Long roleId :roleIds){
//                if(roleId==null){
//                    continue;
//                }
                //if(roleId!=null && !"".equals(roleId)){
                if(!StringUtils.isEmpty(roleId)){
                    AdminRole adminRole = new AdminRole();
                    adminRole.setAdminId(adminId);
                    adminRole.setRoleId(roleId);
                    this.adminRoleDao.insert(adminRole);
                }

            }
        }
    }
}
